<template>
  <div
    class="absolute top-0 bottom-0 left-0 right-0 overflow-y-auto bg-no-repeat bg-center bg-cover bg-[url(https://kposshzcdn.ckjr001.com/admin/material/14_material_admin/image/assets/loginBanner/homepage_basemap.png)]"
  >
    <div
      class="overflow-auto pb-15 absolute left-0 min-h-730 size-full flex flex-col justify-between"
    >
      <div class="pt-15 pl-15 mp-ph0 mp-pb0">
        <a href="http://www.ckjr001.com" target="blank">
          <img src="@/assets/logo/logo.svg" height="28" alt="" srcset="" />
        </a>
      </div>
      <div class="mt-0 mb-0 ml-auto mr-auto flex rounded-10 overflow-hidden mp-w100 mp-mt20">
        <div v-loading="loginPageConfigLoading" class="w-500 h-500 mr-100 mp-hide">
          <img
            v-if="loginPageConfigImage"
            :src="loginPageConfigImage"
            class="size-full pt-40"
            alt=""
            srcset=""
          />
        </div>
        <div
          class="w-500 h-600 bg-white p-50 rounded-12 shadow-[0_2px_8px_0_rgba(0,0,0,0.02)] mp-w100"
        >
          <div class="text-32 text-333333 font-bold mb-17">欢迎来到创客匠人</div>
          <div class="text-14 text-333333 mb-50">
            没有账号？
            <span class="text-accent-color cursor-pointer" @click="linkToRegister">立即注册</span>
          </div>
          <div class="flex mb-4">
            <div
              v-for="(item, index) in loginTypeOption"
              :key="index"
              class="pb-7 mr-30 text-center text-16 cursor-pointer"
              :class="
                loginType === item.value
                  ? 'border-b-2 border-solid border-accent-color text-accent-color font-bold'
                  : 'text-333333'
              "
              @click="changeLoginType(item)"
            >
              {{ item.label }}
            </div>
          </div>
          <el-form ref="loginFormRef" :model="loginFormData" :rules="loginRules">
            <template v-if="loginType == 'password'">
              <el-form-item prop="username">
                <el-input
                  v-model="loginFormData.username"
                  size="large"
                  placeholder="请输入账号或手机号码"
                  class="pt-23"
                />
              </el-form-item>
              <input class="hidden" type="text" name="remembered" />
              <input class="hidden" type="password" name="remembered" />
              <el-form-item class="relative" prop="password">
                <template v-if="isAdminLogin">
                  <el-input
                    v-if="invisible"
                    v-model="passwordValue"
                    type="text"
                    size="large"
                    placeholder="请输入密码"
                    @compositionend.native="compositionend"
                    @compositionstart.native="compositionstart"
                    @input.native="inputVal"
                  />
                  <el-input
                    v-else
                    v-model="pwd"
                    size="large"
                    type="text"
                    placeholder="请输入密码"
                  />
                </template>
                <el-input
                  v-else
                  v-model="loginFormData.password"
                  size="large"
                  name="password"
                  :type="passwordType"
                  autocomplete="off"
                  placeholder="请输入密码"
                />
                <span
                  class="h-full leading-44 absolute right-15 top-0 text-16 text-889aa4 cursor-pointer select-none"
                  @click="showPwd"
                >
                  <svg-icon v-if="invisible" icon-class="eye" />
                  <el-icon v-else><View /></el-icon>
                </span>
              </el-form-item>
              <el-form-item class="relative" prop="captcha">
                <el-input
                  v-model="loginFormData.captcha"
                  size="large"
                  name="captcha"
                  type="text"
                  maxlength="14"
                  placeholder="请输入验证码"
                  @keyup.enter.native="handleLogin"
                />
                <img
                  v-show="captchaImg"
                  :src="captchaImg"
                  title="点击图片重新获取验证码"
                  class="absolute w-120 h-30 bottom-5 right-15 text-center cursor-pointer"
                  @click="loadCaptcha"
                />
              </el-form-item>
              <div class="flex justify-between items-center">
                <div v-if="!isAdminLogin || !loginFormData.username" class="flex items-center">
                  <el-checkbox v-model="checked">
                    <div class="text-12 text-333333 flex items-center">记住密码</div>
                  </el-checkbox>
                </div>
                <div v-else />
                <div class="text-12 cursor-pointer text-accent-color" @click="modifyPassword">
                  忘记密码
                </div>
              </div>
            </template>
            <template v-else>
              <el-form-item prop="mobile">
                <el-input
                  v-model.trim="loginFormData.mobile"
                  size="large"
                  class="mt-23"
                  name="mobile"
                  type="text"
                  placeholder="请输入手机号码"
                />
              </el-form-item>
              <el-form-item class="relative" prop="captcha">
                <el-input
                  v-model="loginFormData.captcha"
                  size="large"
                  name="captcha"
                  type="text"
                  maxlength="14"
                  placeholder="请输入验证码"
                />
                <img
                  v-show="captchaImg"
                  :src="captchaImg"
                  title="点击图片重新获取验证码"
                  class="absolute w-120 h-30 bottom-5 right-15 text-center cursor-pointer"
                  @click="loadCaptcha"
                />
              </el-form-item>
              <el-form-item class="relative" prop="code">
                <el-input
                  v-model="loginFormData.code"
                  size="large"
                  name="code"
                  type="text"
                  maxlength="16"
                  placeholder="请输入验证码"
                  @keyup.enter.native="handleLogin"
                />
                <el-button
                  :disabled="isClick || loginFormData.captcha.length < 4"
                  class="absolute w-100 h-20 bottom-3 right-15 text-center rounded-none cursor-pointer"
                  type="text"
                  @click="getYzcode"
                >
                  {{ yzText }}
                </el-button>
              </el-form-item>
            </template>
            <div :class="loginType == 'password' ? 'pt-15' : ''">
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                class="w-full shadow-[0_5px_15px_0_rgba(64,158,255,0.2)]"
                size="large"
                :class="{
                  active: loginFormData.username && loginFormData.password && loginFormData.captcha,
                }"
                type="primary"
                @click.native.prevent="handleLogin"
              >
                {{ $t("login.login") }}
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="text-center text-999999 text-14 mt-10">
        <div class="pb-10">{{ $t("systemDesc") }}</div>
        <div>{{ $t("systemCopyright") }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AuthAPI, { type LoginFormData, UserInfo } from "@/api/auth";
import { FormInstance } from "element-plus";
import { isPhoneNumber } from "@/utils";
import { useUserStore } from "@/store";
import router from "@/router";

const { t } = useI18n();
// 登录页图片
const loginPageConfigImage = ref<string>("");
// 获取图片添加加载状态
const loginPageConfigLoading = ref<boolean>(false);
// 重新获取验证码
const loginPageConfig = () => {
  if (loginPageConfigLoading.value) return;
  loginPageConfigLoading.value = true;
  AuthAPI.loginPageConfig()
    .then((data) => {
      loginPageConfigLoading.value = false;
      loginPageConfigImage.value = data.image;
    })
    .catch(() => {
      loginPageConfigLoading.value = false;
    });
};
// 用户状态管理器
const userStore = useUserStore();
// 表单Ref
const loginFormRef = ref<FormInstance>();
// 登录类型列表
const loginTypeOption = ref<OptionType[]>([
  { label: "密码登录", value: "password" },
  { label: "验证码登录", value: "code" },
]);
// 选择登录类型
const loginType = ref<string>("password");
//改变登录类型
function changeLoginType(item: OptionType) {
  loadCaptcha();
  loginType.value = item.value as string;
  loginFormRef.value?.clearValidate();
}
// 登录表单参数
const loginFormData = ref<LoginFormData>({
  username: "",
  password: "",
  captchaKey: "",
  captcha: "",
  code: "",
  mobile: "",
});
const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
    ],
    captcha: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
    code: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
    mobile: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.mobile.required"),
      },
    ],
  };
});
// 密码类型
const passwordType = ref<string>("password");
// 是否显示密码
const invisible = ref<boolean>(true);
// 输入密码
const passwordValue = ref<string>("");
// 输入密码
const pwd = ref<string>("");
// 是否中文输入法
const chineseStatus = ref<boolean>(false);
// 是否是总部管理员账号登录
const isAdminLogin = computed(() => {
  return loginFormData.value.username && loginFormData.value.username.trim().includes("admin");
});
// 原数据逻辑监听用户名是否变更 变更重新对密码进行替换操作
watch(
  () => loginFormData.value.username,
  (newValue) => {
    if (newValue && newValue.trim().includes("admin")) {
      passwordValue.value = loginFormData.value.password;
      replacePwd(passwordValue.value);
    }
  },
  { deep: true }
);
// 原数据逻辑监听密码是否变更 变更重新对密码进行替换操作
watch(
  () => pwd.value,
  (newValue) => {
    passwordValue.value = newValue;
    loginFormData.value.password = newValue;
    replacePwd(newValue);
  }
);
// 中文输入法输入结束执行事件
const compositionend = () => {
  chineseStatus.value = false;
  replacePwd(passwordValue.value);
};
// 中文输入法开始输入执行事件
const compositionstart = () => {
  chineseStatus.value = true;
  replacePwd(pwd.value);
};
// 英文输入法执行事件
const inputVal = () => {
  if (!chineseStatus.value) {
    replacePwd(passwordValue.value);
  }
};
// 显示隐藏密码方法
const showPwd = () => {
  if (passwordType.value === "password") {
    passwordType.value = "";
    invisible.value = false;
  } else {
    passwordType.value = "password";
    invisible.value = true;
  }
};
// 替换密码方法
const replacePwd = (newVal: string) => {
  if (pwd.value === "" && newVal && newVal.indexOf("●") === -1) {
    pwd.value = newVal;
  }
  if (
    pwd.value &&
    pwd.value.trim().length > 0 &&
    pwd.value.trim().length !== newVal.trim().length
  ) {
    let data = newVal.split("");
    let count = 0;
    for (let i = 0; i < data.length; i++) {
      if (data[i] == "●") {
        data[i] = pwd.value[i - count];
      } else {
        count += 1;
      }
    }
    newVal = data.join("");
    pwd.value = newVal;
    loginFormData.value.password = pwd.value;
  }
  let str = "";
  for (let j = 0; j < newVal.length; j++) {
    str += "●";
  }
  passwordValue.value = str;
};
// 验证码图片
const captchaImg = ref<string>("");
// 登录方法
const handleLogin = () => {
  // 如果登录方式为验证码登录判断是否输入正确的手机号
  if (loginType.value === "code" && !isPhoneNumber(loginFormData.value.mobile)) {
    ElMessage.warning("请填写正确的手机号");
    return;
  }
  // 如果登录账号为管理员admin则不允许记住密码
  if (isAdminLogin.value) {
    checked.value = false;
  }
  // 判断是否勾选记住密码 如果是调用配置cookie方法
  if (checked.value) {
    setCookie(loginFormData.value.username, loginFormData.value.password, 7);
  } else {
    setCookie("", "", -1);
  }
  // 验证表单参数是否正确
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (fullscreenLoading.value) return;
      fullscreenLoading.value = true;
      if (loginType.value === "password") {
        userStore
          .login(loginFormData.value)
          .then(async (res) => {
            fullscreenLoading.value = false;
            getUserInfo(res);
          })
          .catch(() => {
            loadCaptcha();
            fullscreenLoading.value = false;
          })
          .finally(() => {
            fullscreenLoading.value = false;
          });
      } else {
        userStore
          .loginByMobile(loginFormData.value)
          .then(async (res) => {
            fullscreenLoading.value = false;
            getUserInfo(res);
          })
          .catch(() => {
            loadCaptcha();
            fullscreenLoading.value = false;
          })
          .finally(() => {
            fullscreenLoading.value = false;
          });
      }
    } else {
      loadCaptcha();
      fullscreenLoading.value = false;
    }
  });
};
// 获取用户信息
const getUserInfo = (type: string) => {
  if (type === "login") {
    userStore.getUserInfo().then((data) => {
      const roles: string[] = data.roles;
      if (roles.indexOf("root") == -1 && roles.indexOf("admin") == -1) {
        if (window.location.host.includes("localhost")) {
          // 本地运行环境
          ElMessageBox.alert("本地运行环境暂不支持登入商家系统", "提示", {
            confirmButtonText: "确定",
            center: true,
            callback: () => {
              userStore.logout().then(() => {
                location.reload();
                router.push("/login");
              });
            },
          });
        } else {
          document.location.href = "https://" + window.location.host + "/dashboard";
        }
        return;
      }
      router.push("/");
    });
  } else if (type === "selectShop") {
    router.push("/selectShop");
  }
};
// 设置cookie
const setCookie = (c_name: string, c_pwd: string, exdays: number) => {
  let exdate = new Date(); // 获取时间
  exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); // 保存的天数
  let isSecure = document.location.protocol == "https:";
  // 字符串拼接cookie
  window.document.cookie =
    "userName" +
    "=" +
    c_name +
    ";path=/;expires=" +
    exdate.toUTCString() +
    `${isSecure ? ";secure=true" : ""}`;
  window.document.cookie =
    "userPwd" +
    "=" +
    c_pwd +
    ";path=/;expires=" +
    exdate.toUTCString() +
    `${isSecure ? ";secure=true" : ""}`;
};
// 读取cookie
const getCookie = () => {
  if (document.cookie.length > 0) {
    // 这里显示的格式需要切割一下自己可输出看下
    let arr = document.cookie.split("; ");
    for (let i = 0; i < arr.length; i++) {
      // 再次切割
      let arr2 = arr[i].split("=");
      // 判断查找相对应的值
      if (arr2[0] == "userName") {
        // 保存到保存数据的地方
        loginFormData.value.username = arr2[1];
      } else if (arr2[0] == "userPwd") {
        loginFormData.value.password = arr2[1];
      }
    }
  }
};
// 重新获取验证码
const loadCaptcha = () => {
  AuthAPI.getCaptcha().then((data) => {
    loginFormData.value.captchaKey = data.key;
    captchaImg.value = data.img;
  });
};
// 是否记住密码
const checked = ref<boolean>(false);
// 跳转至修改密码
const modifyPassword = () => {};
// 是否点击登录
const fullscreenLoading = ref<boolean>(false);
// 立即注册
const linkToRegister = () => {};
// 是否允许点击
const isClick = ref<boolean>(false);
// 验证名称
const yzText = ref<string>("获取验证码");
// 倒计时定时器
const interval = ref<NodeJS.Timeout | null>(null);
// 倒计时时间
const num = ref<number>(60);
// 获取短信验证码
const getYzcode = () => {
  if (!loginFormData.value.mobile) {
    ElMessage.warning("请输入手机号");
    return;
  }
  if (!isPhoneNumber(loginFormData.value.mobile)) {
    ElMessage.warning("请填写正确的手机号");
    return;
  }
  if (isClick.value) return;
  isClick.value = true;
  yzText.value = "正在发送短信";
  AuthAPI.getMobileCode(loginFormData.value).then((data) => {
    interval.value = setInterval(getYzMethod, 1000);
    ElMessage.success("短信发送成功");
  });
};
// 倒计时
const getYzMethod = () => {
  num.value -= 1;
  yzText.value = num.value + "秒后重新获取";
  if (num.value == 0) {
    isClick.value = false;
    clearInterval(interval.value!);
    yzText.value = "获取验证码";
    num.value = 60;
  }
};
onMounted(() => {
  loginPageConfig();
  loadCaptcha();
  getCookie();
  if (loginFormData.value.username && loginFormData.value.password) {
    checked.value = true;
  }
  if (sessionStorage.getItem("registMobile") || sessionStorage.getItem("registPassword")) {
    loginFormData.value.username = sessionStorage.getItem("registMobile") || "";
    loginFormData.value.password = sessionStorage.getItem("registPassword") || "";
  }
});
</script>

<style scoped lang="scss"></style>
